package com.weina.controller.admin;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weina.entity.Menu;
import com.weina.entity.Role;
import com.weina.service.EmployeeService;
import com.weina.service.MenuService;
import com.weina.service.RoleService;
import com.weina.utils.DataGridViewResult;
import com.weina.utils.SystemConstant;
import com.weina.utils.TreeNode;
import com.weina.vo.RoleVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/role")
public class RoleController {
    @Resource
    private RoleService roleService;
    @Resource
    private EmployeeService employeeService;
    @Resource
    private MenuService menuService;


    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public DataGridViewResult RoleList(RoleVo roleVo){
        //设置分页参数
        PageHelper.startPage(roleVo.getPage(),roleVo.getLimit());
        List<Role> list=roleService.findRoleList(roleVo);
        PageInfo<Role> page = new PageInfo<>(list);
        return new DataGridViewResult(page.getTotal(),page.getList());
    }
    @RequestMapping(value = "/addRole",method = RequestMethod.POST)
    public String addRole(Role role){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roleService.addRole(role)>0){
            map.put(SystemConstant.SUCCESS,true);
            map.put(SystemConstant.MESSAGE,"添加成功");
        }else{
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"添加失败");
        }
        return JSON.toJSONString(map);
    }
    @RequestMapping(value = "/updateRole",method = RequestMethod.PUT)
    public String updateRole(Role role){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roleService.updateRole(role)>0){
            map.put(SystemConstant.SUCCESS,true);
            map.put(SystemConstant.MESSAGE,"修改成功");
        }else{
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"修改失败");
        }
        return JSON.toJSONString(map);
    }
    @RequestMapping("/checkRoleHasEmployee")
    public String checkRoleHasEmployee(Integer id){
        Map<String,Object> map = new HashMap<String,Object>();
        if(employeeService.getEmployeeCountByRoleId(id)>0){
            map.put(SystemConstant.EXIST,true);
            map.put(SystemConstant.MESSAGE,"该角色存在员工，无法删除");
        }else{
            map.put(SystemConstant.EXIST,false);
        }
        return JSON.toJSONString(map);
    }
    @RequestMapping(value = "/deleteRole",method = RequestMethod.DELETE)
    public String deleteRole(Integer id){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roleService.deleteRole(id)>0){
            map.put(SystemConstant.SUCCESS,true);
            map.put(SystemConstant.MESSAGE,"删除成功");
        }else{
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"删除失败");
        }
        return JSON.toJSONString(map);
    }

    /**
     * 初始化菜单树
     * @return
     */
    @RequestMapping("/initMenuTree/{roleId}")
    public DataGridViewResult initMenuTree(@PathVariable("roleId") Integer roleId){
        //查询所有的菜单
        List<Menu> menuList = menuService.findMenuList();

        //根据当今角色 id 查询 该角色拥有的菜单 id 列表，然后打勾
        List<Integer> currentRoleMenuIds=menuService.findMenuIdListByRoleId(roleId);
        //定义数组列表，保存查询的菜单列表
        List<Menu> currentMenus=new ArrayList<Menu>();

        if(currentRoleMenuIds!=null && currentRoleMenuIds.size()>0){
            //根据菜单id列表，遍历查询菜单详情的集合
            currentMenus=menuService.findMenuByMenuId(currentRoleMenuIds);
        }

        List<TreeNode> treeNodes = new ArrayList<TreeNode>();
        for(Menu menu:menuList){
            String checkArr="0";
            //遍历对比  当前角色 拥有的 菜单 并且给他打勾
            for(Menu cmenu:currentMenus){
                if(menu.getId() == cmenu.getId()){
                    checkArr="1";
                    break;
                }
            }
            //是否展开菜单
            Boolean spread=(menu.getSpread()==null || menu.getSpread()==1 ? true : false);
            treeNodes.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),spread,checkArr));
        }

        return new DataGridViewResult(treeNodes);
    }
    @RequestMapping("/saveRoleMenu")
    public String saveRoleMenu(@Param("mids") String mids,@Param("roleId") Integer roleId){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roleService.saveRoleMenu(mids,roleId)>0){
            map.put(SystemConstant.SUCCESS,true);
            map.put(SystemConstant.MESSAGE,"权限保存成功");
        }else{
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"权限保存失败");
        }
        return JSON.toJSONString(map);
    }
    //初始化用户拥有的 角色列表
    @RequestMapping("/initRoleListByEmpId/{eid}")
    public DataGridViewResult initRoleListByUserId(@PathVariable("eid") Integer eid){
        //查询所有角色列表
        List<Map<String,Object>> roleList= roleService.findRoleListByMap();
        List<Integer> currentEmpRoleList= roleService.findCurrentEmpRoleList(eid);

        for(Map<String,Object> map:roleList){
            boolean flag=false;
            Integer rid=(Integer) map.get("id");//id是主键，以主键作为 map 集合中 key
            for (Integer roleid:currentEmpRoleList){
                if(rid == roleid){
                    flag=true;
                    break;
                }
            }
            // 将状态保存到 map 集合中
            map.put("LAY_CHECKED",flag);
        }

        return new DataGridViewResult(Long.valueOf(roleList.size()),roleList);
    }
}
